﻿using DayuCode.Designer.Common;
using DayuCode.Designer.Entity;
using DayuCode.Designer.Service;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DayuCode.Designer.Forms.template
{
    public partial class FormCodeTemplate : UIForm
    {
        CodeTemplate codeTemplate;
        bool saved = false;
        public FormCodeTemplate(long pageLayoutId, long? codeTemplateId)
        {
            InitializeComponent();

            this.codeTemplate = CodeTemplateHandler.getCodeTemplate(codeTemplateId);
            if(codeTemplateId == null)
            {
                codeTemplate.LayoutId = pageLayoutId;
            }
            cmbCodeType.DataSource = codeTemplate.CodeTypes;
            cmbFileParamType.DataSource = codeTemplate.FileParamTypes;

            txtSummary.Text = codeTemplate.Summary;
            txtOrdnum.Text = "" + codeTemplate.Ordnum;
            txtFilePath.Text = codeTemplate.FilePath;
            txtCodeTemplateText.Text = codeTemplate.CodeTemplateText;

            cmbCodeType.SelectedItem = (cmbCodeType.DataSource as List<CodeItem>).Find(item=>item.Code == codeTemplate.CodeType);
            cmbFileParamType.SelectedItem = (cmbFileParamType.DataSource as List<CodeItem>).Find(item => item.Code == codeTemplate.FileParamType);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string filePath = txtFilePath.Text.Trim();
            if (string.IsNullOrWhiteSpace(filePath))
            {
                this.ShowErrorTip("文件路径不能为空");
                return;
            }
            string prix = string.Format("<#--{0}-->",filePath);
            string ftltext = txtCodeTemplateText.Text;
            if (!ftltext.StartsWith(prix))
            {
                this.ShowErrorTip("当前代码可能不属于此文件模板，第一行不是文件路径:\n" + prix+"\r\n已取消保存。", 3000);
                return;
            }
            codeTemplate.Summary = txtSummary.Text.Trim();
            codeTemplate.CodeType = (cmbCodeType.SelectedItem as CodeItem).Code;
            codeTemplate.FileParamType = (cmbFileParamType.SelectedItem as CodeItem).Code;
            codeTemplate.Ordnum = Cast.ToInt32(txtOrdnum.Text, 0);
            codeTemplate.FilePath = filePath;
            codeTemplate.CodeTemplateText = ftltext;
            CodeTemplateHandler.saveCodeTemplate(codeTemplate);
            saved = true;
            (this.FindForm() as UIForm).ShowSuccessTip("保存成功！");
        }

        public CodeTemplate CodeTemplate
        {
            get { return codeTemplate; }
        }

        private void FormCodeTemplate_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(saved)DialogResult = DialogResult.OK;
        }
    }
}
